package net.jueb.sniff4j.impl.http.filter;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;

import java.io.IOException;

import net.jueb.sniff4j.extr.base.AbstractRuntime;
import net.jueb.sniff4j.extr.filter.DefaultObjectFilter;

public abstract class HttpObjectFilter extends DefaultObjectFilter{
	private String userNmae=getUserContext().getUser().getName();
	private String from=getFromChannel().remoteAddress().toString();
	private String to=getToChannel().remoteAddress().toString();
	protected String info=userNmae+"{"+from+"=>"+to+"}:\n";
	
	
	public HttpObjectFilter(Channel fromChannel, Channel toChannel,AbstractRuntime runtime) {
		super(fromChannel, toChannel, runtime);
	}
	protected String getHeadersString(HttpHeaders headers)
	{
		StringBuffer sb=new StringBuffer();
		for(String headName:headers.names())
		{
			sb.append(headName+":"+headers.get(headName)+"\n");
		}
		return sb.toString();
	}
	/**
	 * 获取返回字节数据，未做任何处理
	 * @param response
	 * @return
	 */
	protected byte[] getContent(DefaultFullHttpResponse response)
	{
		byte[] data=new byte[0];
		if(response.content().isReadable())
		{
			ByteBuf buf=response.content();
			buf.markReaderIndex();//标记读取前的位置
			int length=response.content().readableBytes();
			data=new byte[length];
			ByteBufInputStream bis=new ByteBufInputStream(buf, length);
			try {
				bis.readFully(data);
				buf.resetReaderIndex();//复位读取位置
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
			}
		}
		return data;
	}
	/**
	 * 复制数据
	 * @param request
	 * @return
	 */
	protected byte[] getContent(DefaultFullHttpRequest request)
	{
		byte[] data=new byte[0];
		if(request.content().isReadable())
		{
			ByteBuf buf=request.content();
			buf.markReaderIndex();//标记读取前的位置
			int length=request.content().readableBytes();
			data=new byte[length];
			ByteBufInputStream bis=new ByteBufInputStream(buf, length);
			try {
				bis.readFully(data);
				buf.resetReaderIndex();//复位读取位置
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return data;
	}
}
